import style from '@/assets/components.module.scss';

import { useTouchBottom } from '@/components';
import { HttpResponse } from '@/utils';

export interface ProjectProps {
    limit?: number;
    id?: number;
}
type Res = {
    comt: {
        text: string;
        title: string;
        createtime: string;
    };
    user: {
        avatar: string;
        name: string;
        email: string;
    };
}[];

function Items(list?: Res) {
    console.log(list);

    // 判断list
    const ls = list ?? [];
    return ls.map((item) => (
        <li className={style['comments-block']} key={Math.random()}>
            <div className={style['header']}>
                <div className={style['avatar']}>
                    <img src={item.user.avatar} />
                </div>
                <div>
                    <p>
                        <span className='mr-3 font-bold'>{item.user.name}</span>
                        <span className='text-gray-500'>
                            @{item.user.email}
                        </span>
                    </p>
                    <p>{item.comt.createtime}</p>
                </div>
            </div>
            <div>
                <p>{item.comt.text}</p>
            </div>
        </li>
    ));
}

function Project({ limit, id }: ProjectProps) {
    const mit = limit ?? 99999;
    const [bottom] = useTouchBottom(0);
    const [page, set_page] = useState(1);
    const [list, set_list] = useState<React.ReactElement[]>([]);
    const { data: res } = useSwr<HttpResponse<Res>>(
        `com/${id}/${page}`,
        axios.get,
    );

    useEffect(() => {
        set_list([...list, ...Items(res?.data)].slice(0, mit));
    }, [page, res]);
    useEffect(() => {
        if (mit === 99999 && bottom) set_page(page + 1);
    }, [bottom]);

    return (
        <>
            <ul className={style['comments']}>{list}</ul>
        </>
    );
}

export default Project;
